package app.pool.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Utils {

    private static Logger logger = LoggerFactory.getLogger(Utils.class);

    public static void downloadAndEncodeFileName(InputStream in, HttpServletRequest request, HttpServletResponse response,
                                                 String fileName) throws IOException {
        if (fileName == null || fileName.equals("")) {
            fileName = "default";
        }else {
            fileName = encodeFileName(request, fileName);
        }
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename="
                + fileName);
        IOUtils.copy(in, response.getOutputStream());

    }

    public static String encodeFileName(HttpServletRequest request,
            String filename) {

        String browser = request.getHeader("user-agent");
        Pattern pattern = Pattern.compile(".* MSIE.*?;.*");
        Matcher matcherAccount = pattern.matcher(browser);

        boolean matches = matcherAccount.matches();

        String ret = "file";
        try {
            if (matches) {
                ret = java.net.URLEncoder.encode(filename, "utf-8").replace(
                        "+", "%20");
            } else {
                ret = new String(filename.getBytes("UTF-8"), "ISO8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("编码文件名出错，文件名为：" + filename+"，客户端user-agent属性的值为：" + browser, e);
        }
        return ret;
    }

    public static <T,R> List<R> map(List<T> source, java.util.function.Function<T,R> function){
        return source.stream().map(function).collect(Collectors.toList());
    }

    public static void assertNotEmpty(String string) {
        if (string == null || string.equals("")) {
            throw new IllegalArgumentException();
        }
    }

    static public void assertNotNull(Object object) {
        if (object == null) {
            throw new IllegalArgumentException();
        }
    }

}
